<template>
  <div class="home">
    <div class="lay-out">
      <div class="heades">
        <h1 style="color: pink" class="title">fach请求格式化工具</h1>
        <div>
          <el-button
            v-clipboard:copy="codeFormatting3"
            v-clipboard:success="onCopy"
            v-clipboard:error="onError"
            type="primary"
            >复制</el-button
          >
          <el-button type="primary" @click="FachHAndler">FACH</el-button>
          <el-button type="primary" @click="clearData">全部清空</el-button>
          <el-button type="primary" @click="formattingJson">格式化JSON</el-button>
        </div>
      </div>
      <div class="view-port">
        <div class="pre-code-box">
          <textarea
            v-model="codeFormatting1"
            @input="pre_textarea1"
            id="pre_textarea"
            placeholder="请将代码片段粘贴进此处!"
          ></textarea>
          <textarea
            v-model="codeFormatting2"
            @input="pre_textarea2"
            @focus="pre_textarea2"
            id="pre_textarea"
            placeholder="复制已完成的代码!"
          ></textarea>
          <textarea
            v-model="codeFormatting3"
            @input="pre_textarea3"
            id="pre_textarea"
            placeholder="复制已完成的代码!"
          ></textarea>
        </div>
        <!-- 去掉反斜杠 -->
      </div>
      <!-- json 组件 -->
      <div class="headerview">
        <h1>RESPONES</h1>
        <el-switch
          style="display: block"
          v-model="flag"
          active-color="#5fcb71"
          inactive-color="#e96140"
          active-text="非编辑展示"
          inactive-text="可编辑展示"
          @change="$store.commit('editFlag')"
        >
        </el-switch>
      </div>

      <jsonView v-if="isShow" :json="json"></jsonView>
      <json-editor v-else ref="jsonEditor" v-model="editJson" />

      <!-- <div class="footer-box">
        <h1>相关配置项</h1>
        <ul>
          <li>
            <label>用户代码片段名称 :</label
            ><input
              value="Print to console"
              class="param"
              id="param_name"
              placeholder="用于定义用户代码片段的名称"
            />
          </li>
          <li>
            <label>范围（scope）:</label
            ><input
              class="param"
              id="param_scope"
              placeholder="语言范围（大于两种请用逗号进行隔开）"
            />
          </li>
          <li>
            <label>前缀（prefix）:</label
            ><input
              class="param"
              id="param_prefix"
              placeholder="触发提示的关键词"
            />
          </li>
          <li>
            <label>描述（description）:</label
            ><input
              class="param"
              id="param_description"
              placeholder="相关描述"
            />
          </li>
        </ul>
      </div> -->
      <div class="footer-height"></div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState, mapMutations } from "vuex";
import jsonView from "@/components/JSONVIEW/jsonView.vue";
import JsonEditor from "@/components/JsonEditor";
export default {
  name: "HomeView",
  components: { jsonView, JsonEditor },
  data() {
    return {
      codeFormatting1: "",
      codeFormatting2: "",
      codeFormatting3: "",
      json: {
        暂无数据: "快去发送请求吧",
      },
      editJson: {
        暂无数据: "快去发送请求吧",
      },
      flag:true
    };
  },
  mounted() {
    // 清空数据
    this.codeFormatting1 = "";
    this.codeFormatting2 = "";
    this.codeFormatting3 = "";
    this.codeFormatting1 = this.localCodeFormatting1;
    this.codeFormatting2 = this.localCodeFormatting2;
    this.codeFormatting3 = this.localCodeFormatting3;
    this.flag = this.isShow
  },
  computed: {
    ...mapState([
      "localCodeFormatting1",
      "localCodeFormatting2",
      "localCodeFormatting3",
      "isShow",
    ]),
  },
  methods: {
    ...mapMutations(["clearDataHandler"]),
    pre_textarea2() {
      this.codeFormatting3 = this.handleFormat(this.codeFormatting1);
      this.localFach();
    },
    // 第三个数据处理
    handleFormat(value) {
      let reg1 = /\"/g;
      let reg2 = /\"\{(.+?)\}\"/g; // 获取body 参数然后替换
      // 讲第二个数据处理成str
      console.log('ifes',this.codeFormatting2)
      let res = JSON.stringify(JSON.parse(this.codeFormatting2))
      // 处理第二个数据
      let data2 = '"' + res.replace(reg1, '\\"') + '"';
      let replaceAfter = value
        .replace('"cache-control": "no-cache",', "")
        .replace('"pragma": "no-cache",', "")
        .replace(reg2, data2);
      return replaceAfter;
    },

    // 第二个数据处理
    pre_textarea1() {
      //生名结果
      let result = ''
      let res = ''
      //正则表达式 匹配全部"\" 需要加 /g
      let reg = /\\/g;
      //使用replace方法将全部匹配正则表达式的转义符替换为空 显示更加清楚
      let replaceAfter = this.codeFormatting1.replace(reg, "");
      let reg_a = /\"\[(.+?)\]\"/g
      let reg_o = /\"\{(.+?)\}\"/g
      let isArrayBody = /\"body\": \"\[/g
      if(isArrayBody.test(replaceAfter)) {
        result = replaceAfter.match(reg_a)
        res = result[0].replace('"[', "[").replace(']"', "]");
      }else {
        result = replaceAfter.match(reg_o)
        res = result[0].replace('"{', "{").replace('}"', "}");
      }

      let jsonObj = JSON.parse(res);   //把json字符串转为json对象

      this.codeFormatting2 = JSON.stringify(jsonObj, null, 4); // 序列化数据

      this.localFach();
    },
    pre_textarea3() {
      this.localFach();
    },
    localFach() {
      // 存储数据一
      this.$store.commit("setCodeFormatting1", this.codeFormatting1);
      // 存储数据二
      this.$store.commit("setCodeFormatting2", this.codeFormatting2);
      // 存储数据三
      this.$store.commit("setCodeFormatting3", this.codeFormatting3);
    },
    onCopy() {
      // 复制第3个格式
      this.$message({
        message: "复制FACH格式成功",
        type: "success",
      });
    },
    onError() {
      this.$message({
        message: "复制FACH格式失败",
        type: "error",
      });
    },
    clearData() {
      // 清空数据
      this.codeFormatting1 = "";
      this.codeFormatting2 = "";
      this.codeFormatting3 = "";
      this.clearDataHandler();
    },
    // 发送数据
    async FachHAndler() {
      eval(this.codeFormatting3)
        .then((res) => res.json())
        .then((res) => {
          if (!res) return;
          this.json = res;
          this.editJson = res;
          console.log(res);
        });
    },
    // 格式化JSon
    formattingJson() {
      this.$router.push('/formattingJson')
    }
  },
};
</script>
<style  lang="scss">
* {
  padding: 0;
  margin: 0;
}

.title {
  text-align: center;
  padding: 10px;
}

.lay-out {
  display: flex;
  flex-direction: column;
}

.view-port {
  display: flex;
  height: 90%;
  width: 100%;
}

textarea {
  box-sizing: border-box;
  padding: 10px;
  font-size: 16px;
}

.pre-code-box {
  flex: 1;
}

.res-code-box {
  flex: 1;
}
#pre_textarea {
  height: 580px;
}

#pre_textarea:nth-of-type(1) {
  width: 20%;
  resize: none;
  background-color: rgb(231, 228, 228);
}

#pre_textarea:nth-of-type(2) {
  width: 45%;
  resize: none;
  background-color: rgb(231, 227, 227);
}
#pre_textarea:nth-of-type(3) {
  width: 35%;
  resize: none;
  background-color: rgb(194, 190, 190);
}
.footer-box {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.footer-box label:nth-child(n) {
  display: inline-block;
  width: 160px;
}

.footer-box input:nth-child(n) {
  box-sizing: border-box;
  padding: 5px;
  height: 24px;
  width: 300px;
}
.heades {
  height: 60px;
  align-items: center;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
}
.footer-height {
  height: 10px;
  width: 100%;
}
.home {
  width: 1390px;
  margin: auto;
}
.headerview {
  display: flex;
  align-items: center;
  padding: 20px 0;
  h1 {
  margin-right: 20px;
  }
}
</style>
